package util.concurrent;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 队列在线
 */
public class Base2 {
    ReentrantLock lock = new ReentrantLock();

    Condition give = lock.newCondition();

    Condition get = lock.newCondition();

    List<String> list = new LinkedList<>();


    public static void main(String[] args) {
        Base2 base = new Base2();

        for (int i = 1; i <= 10; i++) {
            new Thread(base::give).start();
        }

        for (int i = 1; i <= 20; i++) {
            new Thread(base::get).start();
        }
    }

    /**
     * 生产
     */
    void give() {
        while (!Thread.interrupted()) {
            lock.lock();
            try {
                if (list.size() == 0) {
                    System.out.println("生产面包");
                    list.add("面包");
                    get.signal();
                } else {
                    try {
                        System.out.println("面包过多停止生产");
                        give.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }

    /**
     * 消费
     */
    void get() {
        while (!Thread.interrupted()) {
            lock.lock();
            try {
                if (list.size() == 0) {
                    try {
                        System.out.println("没有面包");
                        get.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("吃面包");
                    list.remove(0);
                    give.signal();
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
